#!/usr/bin/python
import sys
import os

# read in the file.
fin = open(sys.argv[1],"rb")
lines = fin.readlines()
fin.close()

# pull left and right
id1 = "#0/1"
id2 = "#0/2"
db = {}

'''
1: Shortened forward read name
2: Contig (1) mapped too.
3: Read position (true means it "should" be the first of the pairs)
4: Map orientation (true means it mapped on the the forward start relative to the contig)
5: Map position within (2)

6: Shortened forward read name
7: Contig (6) mapped too.
8: Read position (false means it "should" be the second of the pairs)
9: Map orientation (true means it mapped on the the forward start relative to the contig)
10: Map position within (7) 
'''

idx = 0
for line in lines:
	idx += 1
	if idx % 1000000 == 0:
		print "%i of %i" % (idx, len(lines))
	
	if line[0] == "@": continue
	
	tmp = line.split()
	qname = tmp[0]
	tname = tmp[2]
	
	if tmp[0].count(id1) > 0:
		rtype = "true"
	else:
		rtype = "false"
	
	
	if tmp[1] == "+":
		orien = "true"
	else:
		orien = "false"
		
	pos = tmp[3]
	
	#print qname, tname, rtype, orien
	#print orien
	#print tmp
	
	# check if base name in db.
	bname = qname.replace(id1,"").replace(id2,"")
	if bname not in db:
		db[bname] = [True,True]
	
	# skip if eighter is false.
	if db[bname][0] == False or db[bname][1] == False:
		continue
	
	# check if foudn before.
	if rtype == "true":
		if db[bname][0] != True:
			db[bname][0] = False
			continue
		
		# add entry.
		db[bname][0] = (qname, tname, rtype, orien, pos)
		
	else:
		if db[bname][1] != True:
			db[bname][1] = False
			continue
		
		# add entry.
		db[bname][1] = (qname, tname, rtype, orien, pos)		
			
	
fout = open(sys.argv[2], "wb")
for entry in db:
	# only print double mapped.
	if db[entry][0] != True and db[entry][0] != False and db[entry][1] != True and db[entry][1] != False:
		tmp = '\t'.join(db[entry][0]) + "\t"
		tmp += '\t'.join(db[entry][1])
		fout.write("%s\n" % tmp)
fout.close()
